import axios from "axios"
import type { AxiosRequestConfig } from "axios"

const isPrd = import.meta.env.PROD

export const instance = axios.create({
  baseURL: isPrd ? "http://localhost:7001" : undefined,
})

instance.defaults.timeout = 10000

// prettier-ignore
instance.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"
instance.interceptors.response.use((resp) => {
  return resp
})

function getUrlByEnv(url: string) {
  return isPrd ? url : `/api${url}`
}

export async function postRequest<T>(
  url: string,
  data?: any,
  opt?: AxiosRequestConfig
): Promise<Resp<T>> {
  const res = await instance.post(getUrlByEnv(url), data, opt)
  return res.data
}

export async function getRequest<T>(
  url: string,
  opt?: AxiosRequestConfig
): Promise<Resp<T>> {
  const res = await instance.get(getUrlByEnv(url), opt)
  return res.data
}
